package com.config;

import com.utils.HttpServerUtils;
import com.utils.JwtTokenUtil;
import jakarta.annotation.Resource;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import java.io.IOException;

@Component
public class JwtInterceptor implements HandlerInterceptor {

    @Resource
    private JwtTokenUtil jwtTokenUtil;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws IOException, ServletException {
        System.out.println("preHandle: " + request.getRequestURI());
        String authorization = request.getHeader(HttpServerUtils.tokenKey);
        System.out.println(HttpServerUtils.tokenKey + ": " + authorization);

        boolean result = !jwtTokenUtil.isTokenExpired(request); //检查 token 是否有效且未到期
        if (!result) { //请求转发或发送异常
//            response.sendError(HttpURLConnection.HTTP_UNAUTHORIZED, "认证失败");
            request.getRequestDispatcher("/error/Authorization").forward(request, response);
        }
        return result;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) {
        System.out.println("postHandle: " + request.getRequestURI());
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) {
        System.out.println("afterCompletion: " + request.getRequestURI());
    }
}
